package com.example.test.Service;

//文件复制要用的jar包
import org.apache.commons.io.IOUtils;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;

/**
 * 实现文件的下载功能
 */
@SpringBootApplication
public class Download extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String fileName="马云爸爸.jpg";
        //URL编码(URLEncoder.encode)后文件名才可被浏览器识别
        String downloadFileName = URLEncoder.encode(fileName, "utf-8");
        //通过响应头(resp.setContentType)告诉客户端文件的类型(getServletContext().getMimeType)
        resp.setContentType(getServletContext().getMimeType("/file/"+fileName));
        //告诉客户端文件处理方式(作为附件下载attachment+文件名)
        resp.setHeader("Content-Disposition","attachment;filename="+downloadFileName);
        //读取文件内容的输入流好获取响应的输出流
        InputStream is = getServletContext().getResourceAsStream("/file/"+fileName);
        OutputStream os=resp.getOutputStream();
        //读取流的数据复制给输出流到客户端
        IOUtils.copy(is,os);
    }
}
